<template>
  <div :class="['hm-switch', { 'is-checked': value }]" @click="handleClick">
    <span ref="core" class="hm-switch__core">
      <span class="hm-switch__button"></span>
    </span>
    <input ref="input" class="hm-switch__input" type="checkbox" :name="name" />
  </div>
</template>

<script>
export default {
  name: 'HmSwitch',
  props: {
    value: {
      // v-model 双向数据绑定
      type: Boolean,
      default: false
    },
    activeColor: {
      type: String,
      default: ''
    },
    inactiveColor: {
      type: String,
      default: ''
    },
    name: {
      type: String,
      default: ''
    }
  },
  methods: {
    async handleClick (e) {
      this.$emit('input', !this.value)
      // 点击的时候还需要修改颜色
      // 要等待 value 发生了改变，再 setColor
      // $nextTick 数据修改后，等待 DOM 更新，再修改 Switch 颜色
      await this.$nextTick()
      this.setColor()
      this.$refs.input.checked = this.value
    },
    setColor () {
      // 修改开关的颜色
      if (this.activeColor || this.inactiveColor) { // 确认activeColor或inactiveColor有值
        const color = this.value ? this.activeColor : this.inactiveColor // 根据不同的 value值选用不同的颜色
        this.$refs.core.style.borderColor = color // 更新边框颜色
        this.$refs.core.style.backgroundColor = color // 更新背景颜色
      }
    }
  },
  mounted () {
    this.setColor()
    this.$refs.input.checked = this.value
  }
}
</script>

<style lang="scss">
  .hm-switch {
    display: inline-flex;
    align-items: center;
    position: relative;
    font-size: 14px;
    line-height: 20px;
    height: 20px;
    vertical-align: middle;

    .hm-switch__input {
      position: absolute;
      width: 0;
      height: 0;
      opacity: 0;
      margin: 0;
    }

    .hm-switch__core {
      margin: 0;
      display: inline-block;
      position: relative;
      width: 40px;
      height: 20px;
      border: 1px solid #dcdfe6;
      outline: none;
      border-radius: 10px;
      box-sizing: border-box;
      background: #dcdfe6;
      cursor: pointer;
      transition: border-color 0.3s, background-color 0.3s;
      vertical-align: middle;

      .hm-switch__button {
        position: absolute;
        top: 1px;
        left: 1px;
        border-radius: 100%;
        transition: all 0.3s;
        width: 16px;
        height: 16px;
        background-color: #fff;
      }

    }
  }

  .hm-switch.is-checked {

    .hm-switch__core {
      border-color: #409eff;
      background-color: #409eff;

      .hm-switch__button {
        transform: translateX(20px);
      }

    }
  }
  .hm-switch.is-checked {
    .hm-switch__core {
      border-color: #409eff;
      background-color: #409eff;
      .hm-switch__button {
        transform: translateX(20px);
      }
    }
  }
  .hm-switch__input {
    position: absolute;
    width: 0;
    height: 0;
    opacity: 0;
    margin: 0;
  }
</style>
